﻿using System.Threading;
using X18.Framework.Core.Config;
using X18.Framework.Core.Logs;

namespace X18.Gather.GatherService
{
    public class GatherService
    {
        private int Interval = 5;
        private System.Timers.Timer timer;
        private bool running = false;

        public void Init()
        {
            // 初始化日志
            Logger.Init();
            // 初始化定时器
            Configur.GetInteger("Interval", 5);
        }

        public void Start(string[] args)
        {
            Logger.Info("GatherService", "Starting the service");
            //
            StartTimer();
            //
            Logger.Info("GatherService", "Startup Service completed");
        }

        private void StartTimer()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 1000 * Interval;  //设置计时器事件间隔执行时间
            timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
            timer.Enabled = true;
        }

        public void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            running = true;
            try
            {
                Logger.Info("GatherService", "TimerElapsed");
            }
            finally
            {
                running = false;
            }
        }

        public void Stop()
        {
            Logger.Info("GatherService", "Stoping the service");
            //
            timer.Enabled = false;
            //
            try
            {
                while (running)
                {
                    Thread.Sleep(100);
                }
            }
            catch { }

            //
            Logger.Info("GatherService", "Stop service completed");
        }
    }
}
